var express = require('express');
var router = express.Router();
const UserModel = require("../db/userModel");
var md5 = require('blueimp-md5')
var createtoken = require('../utils/createToken')
//用户注册
module.exports = function (req, res) {
    const {username, password} = req.body
    //查找提交的用户名是否存在
    UserModel.findOne({username:username}, function (error, user) {
        //如果找到了用户
        if (user) {
            res.status(400).send({
                status: 400,
                message: "用户名已存在"
            })
        } else {
            new UserModel({username: username, password: md5(password)}).save(function (error, user) {
                const data = {username: username, _id: user._id}
                res.status(200).send({
                        code: 1,
                        user: {
                            username: data.username,
                            id: data._id,
                            token: createtoken.createToken(user.username, user._id)
                        }
                    }
                )
                // res.redirect('/' + 'user' + username)
            })
        }
    })
}
